package niit.wei.service.impl;

import lombok.extern.slf4j.Slf4j;
import niit.wei.config.RedisConfig;
import niit.wei.entity.User;
import niit.wei.mapper.UserMapper;
import niit.wei.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author WeiJinLong
 * @Date 2023-08-18 11:33
 * @Version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    RedisConfig redisConfig;
    @Resource(name = "redisTemplate")
    HashOperations<String, String, Object> ops;

    public User getUserById1(Integer id) {
        return userMapper.getUserById(id);
    }
    @Override
    public User getUserById(Integer id) {
        User user = null;
        if (!ops.hasKey("user",String.valueOf(id))){
          log.info("Mysql===>");
          user = userMapper.getUserById(id);
          ops.put("user", String.valueOf(id),user);
        }else {
            log.info("Redis===>");
            user = (User) ops.get("user", String.valueOf(id));
        }
        return user;
    }

    @Cacheable(value = {"user"})
    public User getUserById2(Integer id) {
        return userMapper.getUserById(id);
    }

    @Cacheable(value = {"user"},condition = "#id>1")
    public User getUserById3(Integer id) {
        return userMapper.getUserById(id);
    }

    @Cacheable(value = {"user"},unless = "#result.age > 20")
    public User getUserById4(Integer id) {
        return userMapper.getUserById(id);
    }


    @CachePut(value = {"user"},key = "#user.id")
    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }

    @CacheEvict(value = {"user"},key = "#id")
    public int deleteUserById(Integer id){
      return  userMapper.deleteUserById(id);
    }

    @CacheEvict(value = "user",allEntries = true)
    public int  deleteAll(){
        return  userMapper.deleteAll();
    }
}
